package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.maiji.cloud.entities.manager.Role;
import com.maiji.cloud.mapper.RoleMapper;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.request.manager.RoleAddReqData;
import com.maiji.cloud.response.BaseMetaResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.ResMetaData;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.RoleMenuService;
import com.maiji.cloud.service.RoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.service.UserRoleService;
import com.maiji.cloud.utils.UUID_MD5;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public BaseMetaResDto<List<Role>> findAllRoles(String roleName, ReqMetaData metaData) {
        EntityWrapper<Role> entityWrapper = new EntityWrapper<>();
        if (StringUtil.isNotBlank(roleName)) entityWrapper.like("name", roleName);
        Page<Role> rolePage = selectPage(new Page<>(metaData.getPage(), metaData.getSize()), entityWrapper);
        ResMetaData resMetaData = new ResMetaData(rolePage.getCurrent(), rolePage.getSize(), rolePage.getTotal());
        return new BaseMetaResDto<List<Role>>(Status.SUCCESS).setData(rolePage.getRecords()).setResMetaData(resMetaData);
    }

    @Override
    public BaseResDto updRole(Role role) {
        if (updateById(role)) return new BaseResDto(Status.SUCCESS);
        return new BaseResDto(Status.ERROR);
    }

    @Override
    public BaseResDto addRole(RoleAddReqData data) {
        Role role = data.getRole();
        if (! insert(role.setUuId(UUID_MD5.getUUID()))) return new BaseResDto(Status.ERROR);
        List<String> menuIds = data.getMenuIds();
        if (! roleMenuService.addRoleMenus(role.getUuId(), menuIds)) return new BaseResDto(Status.ERROR);
        List<String> userIds = data.getUserIds();
        if (! userRoleService.addUserRoles(role.getUuId(), userIds)) return new BaseResDto(Status.ERROR);
        return new BaseResDto(Status.SUCCESS);
    }

    @Override
    public BaseResDto delRole(String roleId) {
        if (deleteById(roleId)) return new BaseResDto(Status.SUCCESS);
        return new BaseResDto(Status.ERROR);
    }

}
